import api from '../../api/api'
import {productId, goodstocart, cartCount, goodstocheckout } from '../../api/conf'
import Toast from 'tdesign-miniprogram/toast/index';
const WxParse = require('../../wxParse/wxParse.js');

const imgPrefix = "https://we-retail-static-1300977798.cos.ap-guangzhou.myqcloud.com/retail-mp/";

const recLeftImg = `${imgPrefix}common/rec-left.png`;
const recRightImg = `${imgPrefix}common/rec-right.png`;

Page({
  data: {
    goodsId: 0,
    details: null,
    swiperList: [],
    recLeftImg,
    recRightImg,
    soldOut: false,
    showMakePhone: false,
    buttonType: 1,
    buyNum: 1,
    cartNum: 0,
    selectedAttrStr: '',
    selectedLabel: '选择',
    jumpArray: [
      {
        title: '首页',
        url: '/pages/index/index',
        type: 'home',
        iconName: 'home',
      },
      {
        title: '客服',
        type: 'service',
        url: '',
        iconName: 'service',
      },
      {
        title: '购物车',
        type: 'cart',
        url: '/pages/cart/cart',
        iconName: 'cart',
        showCartNum: true,
      },
    ],
    isSpuSelectPopupShow: false,
    specList: [],
    checkSkuIdArr: [],
    navigation: { type: 'fraction' },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
  },
  onLoad: function(options) {
    if(options.id){
      this.setData({
        goodsId: options.id
      })
    }
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    this.getProduct()
  },
  onShow: function () {
    this.getCartNum()
  },

  toNav(e) {
    const { url } = e.detail.data;
    const { type } = e.detail.data;
    switch (type) {
      case 'home':
      case 'cart':
        wx.switchTab({url: url,});
        break;
      case 'service':
        this.openMakePhone();
        break;
    }
  },

  getProduct: function (){
    const goodsId = this.data.goodsId
    api.get(productId, {
      id: goodsId
    }).then(res => {
      const swiperList = []
      const details = res.Data
      if(res.Data.Pictures.length > 0){
        res.Data.Pictures.forEach((item, index) => {
          swiperList.push(item.BigUrl)
        })
      }
      this.setData({
        swiperList,
        details,
        specList: details.Attrs,
        isStock: details.StockQuantity > 0,
        soldOut: details.Published,
        minSalePrice: details.Price,
        maxLinePrice: details.OldPrice
      })
      const article = res.Data.Full;
      let that = this
      WxParse.wxParse('article', 'html', article, that, 5);
      wx.hideLoading()
      wx.hideNavigationBarLoading()
    })
  },

  handlePopupHide() {
    this.setData({
      isSpuSelectPopupShow: false,
    });
  },

  showSkuSelectPopup(type) {
    this.setData({
      buyType: type || 0,
      outOperateStatus: type >= 1,
      isSpuSelectPopupShow: true,
    });
  },

  openMakePhone() {
    this.setData({ showMakePhone: true });
  },

  closeMakePhone() {
    this.setData({ showMakePhone: false });
  },

  handleChooseItem: function ({ detail }) {
    this.setData({
      checkSkuIdArr: detail.checkSkuIdArr,
      selectedLabel: detail.selectedLabel,
      selectedAttrStr: detail.selectedAttrStr
    })
  },

  handleBuyNumChange: function (e) {
    const {value} = e.detail
    this.setData({
      buyNum: value
    })
  },

  getCartNum: function() {
    api.get(cartCount, {}).then(res => {
      this.setData({
        cartNum: res.Data
      })
    })
  },

  handleAddCart: function (e) {
    const eventStatus = this.checkOutEvent()
    if(!eventStatus){
      return
    }
    let {cartNum} = this.data
    let {buyNum} = this.data

    api.post(goodstocart, {
      PId: this.data.goodsId,
      Qty: buyNum,
      AttrValue: JSON.stringify(this.data.checkSkuIdArr)
    }).then( res => {
      cartNum = cartNum + buyNum;
      this.setData({isSpuSelectPopupShow: false, cartNum})
      Toast({
        context: this,
        selector: '#t-toast',
        message: '成功加入购物车',
      });
    })
  },

  gotoBuy: function () {
    const eventStatus = this.checkOutEvent()
    if(!eventStatus){
      return
    }
    api.post(goodstocheckout, {
      PId: this.data.goodsId,
      Qty: this.data.buyNum,
      AttrValue: JSON.stringify(this.data.checkSkuIdArr)
    }).then(res => {
      wx.navigateTo({
        url: '/pages/checkout/checkout',
      })
    }).catch(err => {
      wx.showToast({
        title: err.Content,
        icon: 'none'
      })
    })
  },

  checkOutEvent: function () {
    const {checkSkuIdArr} = this.data
    const {isSpuSelectPopupShow} = this.data

    if(!isSpuSelectPopupShow){
      this.setData({isSpuSelectPopupShow: true })
      return false
    }

    if(checkSkuIdArr.length === 0 || checkSkuIdArr.includes(0)){
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择规格',
      });
      return false
    }
    return true
  }
})